package com.fishery.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.quartz.entity.Task;
import com.fishery.quartz.entity.vo.UpdateTaskVo;
import com.fishery.quartz.mapper.TaskMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.quartz.service.QuartzManager;
import com.fishery.quartz.service.TaskService;
import com.fishery.quartz.util.MyBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ghost
 * @since 2021-02-21
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

	@Autowired
	private TaskMapper taskMapper;

	@Autowired
	private QuartzManager quartzManager;

	@Override
	public List<Task> getAllTasksByStatus(String status) {
		return taskMapper.findAllTasksByStatus(status);
	}

	@Override
	@Transactional
	public boolean createTask(Task task) {
		try {
			// 将任务持久化保存到数据库
			taskMapper.insert(task);
			// 定时器添加任务
			quartzManager.add(task);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	@Transactional
	public boolean stopTask(String id, String jobName, String jobGroup, String modifiedName) {
		try {
			// 更新数据库数据
			taskMapper.updateStautsOfTask(id, "0", modifiedName);
			// 定时器停止任务
			quartzManager.pause(jobName, jobGroup);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	@Transactional
	public boolean removeTask(String id, String jobName, String jobGroup, String modifiedName) {
		try {
			// 删除数据库数据
			taskMapper.updateModifiedNameOfTask(id, modifiedName);
			taskMapper.deleteById(id);
			// 定时器删除任务
			quartzManager.delete(jobName, jobGroup);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	@Transactional
	public boolean resumeTask(String id, String jobName, String jobGroup, String modifiedName) {
		try {
			// 修改数据库中任务的状态
			taskMapper.updateStautsOfTask(id, "1", modifiedName);
			// 恢复定时器中的对应的任务
			quartzManager.resume(jobName, jobGroup);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	@Transactional
	public boolean updateParamsOfTask(UpdateTaskVo vo) {
		try {
			// 查询数据库，获取原本的任务信息
			Task oldTask = taskMapper.selectById(vo.getId());
			if (oldTask == null) {
				return false;
			}
			// 对比修改的信息
			if (!StringUtils.isEmpty(vo.getDescription()) && !vo.getDescription().equals(oldTask.getDescription())) {
				// 有修改任务描述
				oldTask.setDescription(vo.getDescription());
			}
			if (!StringUtils.isEmpty(vo.getJobName()) && !vo.getJobName().equals(oldTask.getJobName())
					|| !StringUtils.isEmpty(vo.getJobGroup()) && !vo.getJobName().equals(oldTask.getJobGroup())
					|| !StringUtils.isEmpty(vo.getRequestUri()) && !vo.getRequestUri().equals(oldTask.getRequestUri())
					|| !StringUtils.isEmpty(vo.getRequestMethod()) && !vo.getRequestMethod().equals(oldTask.getRequestMethod())
					|| !StringUtils.isEmpty(vo.getRequestBody()) && !vo.getRequestBody().equals(oldTask.getRequestBody())) {
				// 修改的是任务名、任务分组名、请求URI、请求体、请求方式其中一个的话，直接采取删除并重新添加的方式
				quartzManager.delete(oldTask.getJobName(), oldTask.getJobGroup());
				MyBeanUtil.copyProperties(vo, oldTask, false);
				quartzManager.add(oldTask);
			} else if (!StringUtils.isEmpty(vo.getCronExpression()) && !vo.getCronExpression().equals(oldTask.getCronExpression())) {
				// 修改的是Cron表达式的话，采取修改方式
				quartzManager.update(oldTask.getJobName(), oldTask.getJobGroup(), vo.getCronExpression());
				oldTask.setCronExpression(vo.getCronExpression());
			}
			oldTask.setModifiedName(vo.getModifiedName());
			// 更新数据库任务信息
			taskMapper.updateById(oldTask);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public Page<Task> getPageOfAllRunningTasks(int current, int size) {
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("job_status", "1");
		Page<Task> page = new Page<>(current, size);
		taskMapper.selectPage(page, wrapper);
		return page;
	}

	@Override
	public Page<Task> getPageOfAllStopTasks(int current, int size) {
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("job_status", "0");
		Page<Task> page = new Page<>(current, size);
		taskMapper.selectPage(page, wrapper);
		return page;
	}


}
